<!-- 审计日志 -->
<template>
  <div class="dashboard-editor-container">
		<el-row style="background: #fff; padding: 16px 16px 0;">
      <connsearch ref="connsearch" :formOptions="formOptions"   @search="search" @reset="reset"/>
      <div class="tabclick">
        <!-- <div class="tabitem" @click="handleClick1()">
          <span>显示日统计趋势<i :class="tab1 ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div> -->
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;">
          <el-tab-pane label="显示日统计趋势" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart :title="'显示日统计趋势'" :chartData="barchartData" @barclick="echartsClick"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="访问用户统计分析" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart :title="'按终端用户统计'" :chartData="pie1Data"  @pieclick="echartsClick"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="按域名统计" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :title="'按域名统计'" :chartData="pie4Data"  @pieclick="echartsClick"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="按域名大分类统计" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :title="'按域名大分类统计'" :chartData="pie2Data"  @pieclick="echartsClick"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="按域名小分类统计" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :title="'按域名小分类统计'" :chartData="pie3Data"  @pieclick="echartsClick"/>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <!-- <barchart /> -->
      
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin: 16px 0;">
        <!-- <span class="title">审计日志列表</span> -->
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="访问时间" prop="TransTime" align="left" width="160px"></el-table-column>
          <el-table-column label="访问终端" prop="EmployeeName" align="left" width="160px"></el-table-column>
          <el-table-column label="域名分类" prop="ClassID" align="left" width="250px"></el-table-column>
          <el-table-column label="域名" prop="URL" show-overflow-tooltip align="left" ></el-table-column>
          <el-table-column label="所在地区" prop="Area" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="审计策略" show-overflow-tooltip align="left" width="120px">
            <template slot-scope="scope">
              <p style="color:#67C23A" v-if="scope.row.AccessType === '加速'">加速</p>
              <p style="color:#909399" v-if="scope.row.AccessType === '直连'">直连</p>
              <p style="color:#F56C6C" v-if="scope.row.AccessType === '禁止'">禁止</p>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { getNowDay, parseTime, getTreeData, ParamDictURLtype, Maintype } from '@/utils/index.js';
import { connrequest } from '@/api/firstPage.js';
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
export default {
  components: { connsearch, barchart, piechart },
  data() {
    return {
      activeName:'按日统计',
      tableData:[],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      tab2: false,
      barchartData: {xAxis:[],series:[]},
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      pie4Data: [],
      searchform:{},
      formOptions:[
        {
          col: 8,
          label: "日期",
          prop: "timeRange",
          element: "el-date-picker",
          initValue: [],
          type: ""
        },
        {
          col: 4,
          label: "统计排名",
          prop: "rank",
          element: "el-select",
          initValue: 10,
          options: [
            { label: '前十名', value: 10 },
            { label: '前二十名', value: 20 },
            { label: '前三十名', value: 30 }
          ],
          events:{
            input (val) {
              console.log(val);
            }
          }
        },
        {
          label: "域名分类",
          prop:"type",
          element: "el-cascader",
          initValue: "",
          placeholder: "请选择域名分类",
          options:[],
          events: {
            input (val) {
              console.log(val);
            }
          }
        },
        {
          label: "终端用户",
          prop: "Name",
          element: "el-select",
          initValue: '',
          placeholder: "请选择终端用户",
          options:[],
          events: {
            input (val) {
              console.log(val);
            }
          }
        },
        {
          col: 8,
          label: "域名描述",
          prop: "URL",
          element: "el-input",
          placeholder: "请输入域名描述,支持模糊查询。",
          events: {
            input (val) {
              console.log(val);
            }
          }
        },
        {
          col: 4,
          label: "审计结果",
          prop: "AccessType",
          element: "el-select",
          initValue: 0,
          placeholder: "请选择审计结果",
          options:[
            { label: "全部", value: 0},
            { label: "禁止", value: 1},
            { label: "加速", value: 2},
            { label: "直连", value: 3}
          ],
          events:{
            input (val) {
              console.log(val)
            }
          }
        }
      ]
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    let xTime = new Date().getTime()
    let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
    // let arr = [ parseTime(startTime), parseTime(xTime)]
    let arr = [ parseTime(xTime), '']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    this.getData()
    this.GetEmployee()
    this.GetParamDictURL()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods:{
    getData(){
      this.GetShadowURLLog()
      this.GetShadowURLSumGroupByUser()
      this.GetShadowURLSumGroupByURL()
      this.GetShadowURLSumGroupByMainClass()
      this.GetShadowURLSumGroupBySubClass()
      this.GetShadowURLSumGroupByDate()
    },
    echartsClick(val, title, id){
      this.pageNum = 1
      if(title === '显示日统计趋势'){
        this.searchform = {...this.$refs.connsearch.searchform, timeRange: [ `${val} 00:00:00`, `${val} 23:59:59` ]}
      }else if(title === '按终端用户统计'){
        this.searchform = {...this.$refs.connsearch.searchform, Name: val}
      }else if(title === '按域名统计'){
        this.searchform = {...this.$refs.connsearch.searchform, URL: val}
      }else if(title === '按域名大分类统计'){
        this.searchform = {...this.$refs.connsearch.searchform, type: val.split('--')}
      }else if(title === '按域名小分类统计'){
        this.searchform = {...this.$refs.connsearch.searchform, type: val.split(' / ')}
      }
      this.GetShadowURLLog()
    },
    // 获取终端用户
    async GetEmployee(){
      const res = await connrequest('GetEmployee')
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.label = item.Name
        item.value = item.Name
        return item
      })
      let arr = [{value: '', label: '全部'}]
      this.formOptions.map( item => {
        if(item.label === '终端用户'){
          item.options = [...arr,...res.Data]
        }
      })
    },
    // 获取域名分类
    async GetParamDictURL(){
      const res = await connrequest('GetParamDictURL')
      this.Options = res.Data
      let arr = []
      let idlist = []
      res.Data = res.Data || []
      res.data = res.Data.map(item => {
        arr.push(item.MainClass)
        idlist.push(item.MainID)
      })
      arr = Array.from(new Set(arr))
      idlist = Array.from(new Set(idlist))
      // 给原数组加根节点
      arr.map((item,index) => {
        res.Data.push({ClassID: 0, MainID: idlist[index], MainClass: "根节点", SubClass: item, CreateEvent: 0})
      })
      this.formOptions.map( item => {
        if(item.label === '域名分类'){
          item.options = getTreeData(this.treeing(res.Data))
        }
      })
    },
    treeing(arr) {
      let res = [] // 存放结果集
      let map = {}
      // 判断对象是否有某个属性
      let getHasOwnProperty = (obj, property) => Object.prototype.hasOwnProperty.call(obj, property)
      // 边做map存储，边找对应关系
      for (const i of arr) {
        map[i.SubClass] = {
            ...i,
            children: getHasOwnProperty(map, i.SubClass) ? map[i.SubClass].children : []
        }
        const newItem = map[i.SubClass]
        if (i.MainClass === '根节点') {
          res.push(newItem)
        } else {
          if (!getHasOwnProperty(map, i.MainClass)) {
            map[i.MainClass] = {
              children: []
            }
          }
          map[i.MainClass].children.push(newItem)
        }
      }
      return res
    },
    // 获取事件日期统计
    async GetShadowURLSumGroupByDate() {
      let xAxis = []
      let series= []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name:'',
          Descp: this.searchform.URL || '',
          SumCount: 10
        }
      }
      const res = await connrequest('GetShadowURLSumGroupByDate', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        xAxis.push(item.Name)
        series.push(item.Count)
      })
      this.barchartData = {xAxis,series}
    },
    // 获取审计用户统计
    async GetShadowURLSumGroupByUser(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate: '',
          AccessType: '0',
          MainClassID: '0',
          ClassID: '0',
          Name:this.searchform.Name || '',
          URL: this.searchform.URL || '',
          SumCount: 10
        }
      }
      const res = await connrequest('GetShadowURLSumGroupByUser', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie1Data = arr
    },
    // 获取域名大类统计
    async GetShadowURLSumGroupByMainClass(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name:this.searchform.Name || '',
          Descp: this.searchform.URL || '',
          SumCount: 10
        }
      }
      const res = await connrequest('GetShadowURLSumGroupByMainClass', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: Maintype(item.ClassID), value: item.Count, id: item.ClassID})
      })
      this.pie2Data = arr
    },
    // 获取域名小类统计
    async GetShadowURLSumGroupBySubClass(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name:this.searchform.Name || '',
          Descp: this.searchform.URL || '',
          SumCount: 10
        }
      }
      const res = await connrequest('GetShadowURLSumGroupBySubClass', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: ParamDictURLtype(item.ClassID), value: item.Count, id: item.ClassID})
      })
      this.pie3Data = arr
    },
    // 获取审计域名统计
    async GetShadowURLSumGroupByURL(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name:this.searchform.Name || '',
          Descp: this.searchform.URL || '',
          SumCount: 10
        }
      }
      const res = await connrequest('GetShadowURLSumGroupByURL', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.URL, value: item.Count})
      })
      this.pie4Data = arr
    },
    // 获取审计日志列表
    async GetShadowURLLog(){
      let arr
      if(this.searchform?.type?.length > 0){
        let subClass = this.searchform?.type[this.searchform?.type?.length - 1]
        arr = this.Options.filter(item => {return item.SubClass === subClass})
      }
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          // TransDate: getNowDay(),
          AccessType: this.searchform.AccessType * 1,
          MainClassID: arr?.length > 0 ? arr[0].MainID * 1 : 0,
          ClassID: arr?.length > 0 ? arr[0].ClassID * 1 : 0,
          TransDate:'',
          Name:this.searchform.Name || '',
          URL: this.searchform.URL || ''
        }
      }
      const res = await connrequest('GetShadowURLLog', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        item.ClassID = ParamDictURLtype(item.ClassID)
        item.TransTime = parseTime(item.TransTime, '{y}-{m}-{d} {h}:{i}:{s}')
        item.AccessType = item.AccessType === 1 ? '禁止' : (item.AccessType === 2 ? '加速' : '直连')
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    handleSizeChange(val){
      this.pageNum = 1
      this.pageSize = val
      this.GetShadowURLLog()
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetShadowURLLog()
    },
    search(val) {
      this.pageNum = 1
      this.searchform = {...val}
      this.getData()
    },
    reset() {
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "域名分类" || item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "统计排名"){
          item.initValue = 10
        }else if(item.label === "审计结果"){
          item.initValue = 0
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleClick() {
      this.tab = !this.tab
    },
    handleClick2() {
      this.tab2 = !this.tab2
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
@import "./components/css/conncss.scss";
</style>